#include "socket.h"
#include "socketmanager.h"
#include "server.h"

#include <QHostAddress>
#include <QDebug>
#include <QException>

/*
 * @brief:
 * @detail:
 */
Socket::Socket(QTcpSocket* socket, QObject *parent)
    : QObject(parent), socket(socket),
      streamer(), handler(this)
{
    qDebug() << "[socket] 新的连接 <IP> "
             << socket->peerAddress().toString() << " <PORT> "
             << socket->peerPort();

    QObject::connect(SingleTon<Server>::getInstance(), &Server::timeout,
                     this, &Socket::heartcheck);

    QObject::connect(socket, &QTcpSocket::readyRead,
                     this, &Socket::onReadyRead);
    QObject::connect(socket, &QTcpSocket::disconnected,
                     this, &Socket::onDisconnected);

    SingleTon<SocketManager>::getReference().append(socket);

}

//Socket::~Socket()
//{
//    delete socket;
//}

void Socket::heartcheck()
{
    try {
        socket->write(streamer.pack(Handler::heartbeat,"heartbeat"));
    } catch (QException e) {
        onDisconnected();
    }

}

/*
 * @brief:
 * @detail:
 */
void Socket::onReadyRead()
{
    streamer.attach(socket->readAll());
    while(1){
        int type;
        QByteArray data;
        if(streamer.unpack(type, data)){
            handler.handle(type, data);
        }else{
            // 失败
            break;
        }
    }
}

/*
 * @brief:
 * @detail:
 */
void Socket::onDisconnected()
{
    qDebug() << "[socket] 断开连接 <IP> "
             << socket->peerAddress().toString() << " <PORT> "
             << socket->peerPort();

    if(!roomid.isEmpty())
        ServerHandlerCloseRoom::closeroom(username,roomid,this);
    SingleTon<SocketManager>::getReference().remove(socket);


    // 回收状态

    handler.reset();
    socket->deleteLater();
    this->deleteLater();
}
